import pytest
import tempfile
import asyncio
from pathlib import Path
from typing import Generator

from fastapi.testclient import TestClient
from shared.config import Settings
from shared.storage import StorageManager
from shared.conversion import ConversionService
from api.app import app


@pytest.fixture(scope="session")
def event_loop():
    """创建事件循环用于异步测试"""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()


@pytest.fixture
def temp_dir():
    """创建临时目录"""
    with tempfile.TemporaryDirectory() as tmp_dir:
        yield Path(tmp_dir)


@pytest.fixture
def test_settings(temp_dir):
    """测试配置"""
    return Settings(
        storage_path=temp_dir / "test_storage",
        file_ttl=300,  # 5分钟
        max_file_size=10 * 1024 * 1024,  # 10MB
        supported_themes=["default", "blue", "dark"],
        default_theme="default"
    )


@pytest.fixture
def storage_manager(test_settings):
    """存储管理器"""
    return StorageManager(test_settings.storage_path, test_settings.file_ttl)


@pytest.fixture
def conversion_service(storage_manager):
    """转换服务"""
    return ConversionService(storage_manager)


@pytest.fixture
def api_client():
    """API 测试客户端"""
    return TestClient(app)


@pytest.fixture
def sample_markdown():
    """示例 Markdown 内容"""
    return """# Test Presentation

## Introduction
- This is a test presentation
- Created for testing purposes
- Multiple bullet points

## Features
- Automatic slide generation
- Theme support
- Media handling

### Technical Details
- Built with Python
- Uses python-pptx library
- Supports multiple formats

## Conclusion
Thank you for testing!
"""


@pytest.fixture
def sample_markdown_file(temp_dir, sample_markdown):
    """创建示例 Markdown 文件"""
    md_file = temp_dir / "test.md"
    with open(md_file, 'w', encoding='utf-8') as f:
        f.write(sample_markdown)
    return md_file


@pytest.fixture
def sample_image_file(temp_dir):
    """创建示例图片文件"""
    from PIL import Image
    
    # 创建一个简单的测试图片
    img = Image.new('RGB', (100, 100), color='red')
    img_file = temp_dir / "test.jpg"
    img.save(img_file)
    return img_file